<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from "vue";
import api from "@/api";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import machineryDetails from "./machineryDetails.vue";
import _ from "lodash";
import { transformTZToLocal } from "@/utils/common.js";

let deviceChartRef = ref();
let myDeviceChart = null;

let showDetail = ref(false);
let currentTag = ref("");

const maintenanceTableRef = ref();
const deviceRecordTableRef = ref();
const maintenanceRecordTableRef = ref();

const deviceData = reactive({
  deviceStat: {
    deviceArr: [
      { value: 85, name: "塔式起重机" },
      { value: 35, name: "施工升降机" },
    ],
  },
  maintenanceTable: [],
  deviceRecord: [],
  maintenanceRecord: [],
  deviceList: [],
});

const pieCharColorList = [
  { c1: "#FFD800", c2: "#FFC529" },
  { c1: "#13B2C2", c2: "#10FECF" },
];

const initDeviceChart = () => {
  let chartDeviceDom = document.getElementById("deviceChart");
  echarts.dispose(chartDeviceDom);
  myDeviceChart = echarts.init(deviceChartRef.value);
  myDeviceChart.clear();
  let option;
  option = {
    tooltip: {
      trigger: "item",
    },
    series: [
      {
        name: "设备",
        type: "pie",
        radius: ["30%", "50%"],
        center: ["58%", "57%"],
        avoidLabelOverlap: false,
        itemStyle: {
          color: function (params) {
            return new echarts.graphic.LinearGradient(0, 1, 0, 0, [
              {
                //颜色渐变函数 前四个参数分别表示四个位置依次为左、下、右、上
                offset: 0,
                color: pieCharColorList[params.dataIndex].c1,
              },
              {
                offset: 1,
                color: pieCharColorList[params.dataIndex].c2,
              },
            ]);
          },
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: true,
          position: "outside",
          color: "#000",
          formatter: function (params) {
            if (params.name !== "") {
              return params.name + "\n" + params.value;
            } else {
              return "";
            }
          },
        },
        labelLine: {
          length: 15,
          length2: 25,
          show: true,
          color: "#000",
        },
        data: deviceData.deviceStat.deviceArr,
      },
    ],
  };
  option && myDeviceChart.setOption(option);
};

const handleTagClick = (item) => {
  if (item.machineCode == "") {
    ElMessage({
      message: "暂无相关信息",
      type: "warning",
    });
    return;
  }
  currentTag.value = item.machineCode;
  let maintenanceIndex = _.findIndex(deviceData.maintenanceTable, [
    "serialNumber",
    item.machineCode,
  ]);
  let deviceRecordIndex = _.findIndex(deviceData.deviceRecord, [
    "serialNumber",
    item.machineCode,
  ]);
  let maintenanceRecodeIndex = _.findIndex(deviceData.maintenanceRecord, [
    "serialNumber",
    item.machineCode,
  ]);
  maintenanceTableRef.value.setCurrentRow(
    deviceData.maintenanceTable[maintenanceIndex]
  );
  handleTableDw("maintenanceTableRef", maintenanceIndex);
  deviceRecordTableRef.value.setCurrentRow(
    deviceData.deviceRecord[deviceRecordIndex]
  );
  handleTableDw("deviceRecordTableRef", deviceRecordIndex);
  maintenanceRecordTableRef.value.setCurrentRow(
    deviceData.maintenanceRecord[maintenanceRecodeIndex]
  );
  handleTableDw("maintenanceRecordTableRef", maintenanceRecodeIndex);
  showDetail.value = true;
};

const handleTableDw = (name, index) => {
  let targetTop;
  let containerTop;
  switch (name) {
    case "maintenanceTableRef":
      targetTop = maintenanceTableRef.value.$el
        .querySelectorAll(".el-table__body tr")
      [index].getBoundingClientRect().top; //该行的位置
      containerTop = maintenanceTableRef.value.$el
        .querySelector(".el-table__body")
        .getBoundingClientRect().top; //body的位置
      maintenanceTableRef.value.setScrollTop(targetTop - containerTop);
      break;
    case "deviceRecordTableRef":
      targetTop = deviceRecordTableRef.value.$el
        .querySelectorAll(".el-table__body tr")
      [index].getBoundingClientRect().top; //该行的位置
      containerTop = deviceRecordTableRef.value.$el
        .querySelector(".el-table__body")
        .getBoundingClientRect().top; //body的位置
      deviceRecordTableRef.value.setScrollTop(targetTop - containerTop);
      break;
    case "maintenanceRecordTableRef":
      targetTop = maintenanceRecordTableRef.value.$el
        .querySelectorAll(".el-table__body tr")
      [index].getBoundingClientRect().top; //该行的位置
      containerTop = maintenanceRecordTableRef.value.$el
        .querySelector(".el-table__body")
        .getBoundingClientRect().top; //body的位置
      maintenanceRecordTableRef.value.setScrollTop(targetTop - containerTop);
      break;
  }
};

const closePanel = () => {
  currentTag.value = "";
  showDetail.value = false;
};

const deviceTotal = computed(
  () =>
    deviceData.deviceStat.deviceArr[0].value +
    deviceData.deviceStat.deviceArr[1].value
);

const initData = () => {
  api.machinery.getAllMachineInfos().then((res) => {
    let resData = res.data;
    let arr = [
      { x: 20, y: 73.38 }, //1
      { x: 53.28, y: 74.25 }, //2
      { x: 26.03, y: 63.27 }, //3
      { x: 55.86, y: 64.45 }, //4
      { x: 26.03, y: 49.92 }, //5
      { x: 54.5, y: 54.34 }, //6
      { x: 54.5, y: 44.15 }, //7
      { x: 30.7, y: 33.25 }, //8
      { x: 58.4, y: 33.73 }, //9
      { x: 30.8, y: 16.59 }, //10
      { x: 57, y: 18.4 }, //11
    ];
    //echart
    deviceData.deviceStat.deviceArr[0].value = _.filter(resData, [
      "machineType",
      "塔式起重机",
    ]).length;
    deviceData.deviceStat.deviceArr[1].value = _.filter(resData, [
      "machineType",
      "施工升降机",
    ]).length;
    initDeviceChart();
    //表1
    deviceData.maintenanceTable = resData.map((item, index) => {
      let last = "";
      if (item.equipmentHistory) {
        let length = item.equipmentHistory.length;
        let date = item.equipmentHistory[length - 1].time;
        last = transformTZToLocal(date);
      }
      return {
        machineType: item.machineType,
        serialNumber: item.serialNumber,
        signDate: transformTZToLocal(item.machineInfo[0].signDate),
        nextDate: last,
      };
    });
    //表2
    deviceData.deviceRecord = resData.map((item, index) => {
      return {
        buildingNo: item.machineInfo[0].buildingNo,
        machineType: item.machineType,
        serialNumber: item.serialNumber,
        cameraStat: item.machineInfo[0].status == "online" ? "在线" : "离线",
      };
    });
    //表3
    let totalArr = [];
    resData.forEach((item) => {
      if (item.equipmentHistory) {
        item.equipmentHistory.forEach((historyItem) => {
          totalArr.push({
            machineType: item.machineType,
            buildingNo: item.machineInfo[0].buildingNo,
            serialNumber: item.serialNumber,
            lastTime: transformTZToLocal(historyItem.time),
            nextTime: transformTZToLocal(historyItem.nextTime),
            expirationTime: "-",
            demolitionTime: "-",
          });
        });
      }
    });
    deviceData.maintenanceRecord = totalArr;
    //绘制点
    let filterData = _.filter(resData, ["machineType", "塔式起重机"]);
    filterData.sort((a, b) =>
      a.machineInfo[0].buildingNo > b.machineInfo[0].buildingNo ? 1 : -1
    );
    deviceData.deviceList = filterData.map((item, index) => {
      return {
        machineType: item.machineType,
        machineCode: item.serialNumber,
        positionX: index <= 12 ? arr[index].y : 0,
        positionY: index <= 12 ? arr[index].x : 0,
      };
    });
    let sub = arr.length - filterData.length;
    if (sub > 0) {
      for (let i = 0; i < sub; i++) {
        deviceData.deviceList.push({
          machineType: "起重机",
          machineCode: "",
          positionX: arr[i + filterData.length].y,
          positionY: arr[i + filterData.length].x,
        });
      }
    }
  });
};

onMounted(() => {
  initData();
  window.onresize = _.debounce(() => {
    myDeviceChart.resize();
  }, 300);
});

// 卸载页面销毁 window.onresize事件
onBeforeUnmount(() => {
  window.onresize = null;
});
</script>

<template>
  <div class="deviceContainer">
    <div class="d-l">
      <div class="deviceChart">
        <div class="title">
          <span>设备统计</span>
        </div>
        <div class="count">
          <img src="@/assets/images/ibe/deviceTotal.png" />
          <span>设备总数：<span class="countSpan">{{ deviceTotal }}</span> 台</span>
        </div>
        <div ref="deviceChartRef" id="deviceChart"></div>
      </div>
      <div class="deviceMaintain">
        <div class="title">
          <span>设备检测表</span>
        </div>
        <el-table :data="deviceData.maintenanceTable" ref="maintenanceTableRef" highlight-current-row
          style="width: 95%; margin: 0 auto; margin-top: 50px" height="250">
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column prop="machineType" label="设备类型" align="center" />
          <el-table-column prop="serialNumber" label="设备编号" align="center" />
          <el-table-column prop="signDate" label="登记日期" align="center" />
          <el-table-column prop="nextDate" label="最近检测日期" align="center" />
        </el-table>
      </div>
      <div class="maintainStat">
        <div class="title">
          <span>设备记录</span>
        </div>
        <el-table :data="deviceData.deviceRecord" ref="deviceRecordTableRef" highlight-current-row
          style="width: 95%; margin: 0 auto; margin-top: 50px" height="250">
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column prop="buildingNo" label="楼栋号" align="center" />
          <el-table-column prop="machineType" label="设备类型" align="center" />
          <el-table-column prop="serialNumber" label="设备编号" align="center" />
          <el-table-column prop="cameraStat" label="摄像头状态" align="center">
            <template #default="scope">
              <span :style="{
                color:
                  scope.row.cameraStat == '在线' ? '#01CE49 ' : '#D3D3D3',
                fontWeight: 600,
              }">{{ scope.row.cameraStat }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="d-r">
      <div class="deviceImg">
        <div class="imgContainer">
          <img class="tagImage" :style="{ top: item.positionY + '%', left: item.positionX + '%' }"
            v-for="(item) in deviceData.deviceList" :key="item.machineCode" src="@/assets/images/ibe/tag.png"
            @click="handleTagClick(item)" />
        </div>
        <div class="modalDevice" v-if="showDetail">
          <machineryDetails :machineCode="currentTag" @close="closePanel"></machineryDetails>
        </div>
      </div>
      <div class="deviceTable">
        <div class="title">
          <span>维保记录</span>
        </div>
        <el-table :data="deviceData.maintenanceRecord" ref="maintenanceRecordTableRef" highlight-current-row
          style="width: 95%; margin: 0 auto; margin-top: 60px" height="320">
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column prop="machineType" label="设备名称" align="center" />
          <el-table-column prop="buildingNo" label="服务楼栋" align="center" />
          <el-table-column prop="serialNumber" label="设备编号" align="center" />
          <el-table-column prop="lastTime" label="最近维保日期" align="center" />
          <el-table-column prop="nextTime" label="下次维保日期" align="center" />
          <el-table-column prop="expirationTime" label="报停日期" align="center" />
          <el-table-column prop="demolitionTime" label="拆除日期" align="center" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.deviceContainer {
  position: relative;
  display: flex;
  width: 100%;
  height: calc(100vh - 85px);
  font-family: SourceHanSansSC;
  color: #656565;
  overflow-x: hidden;
  overflow-y: auto;

  .d-l {
    width: 560px;

    .deviceChart {
      position: relative;
      width: 100%;
      height: 335px;
      border: 1px solid #dce3ef;
      box-shadow: 2px 2px 0px 0px rgba(236, 238, 252, 0.32);
      border-radius: 6px;
      margin-bottom: 8px;
    }

    .maintainStat {
      position: relative;
      width: 100%;
      height: 335px;
      border: 1px solid #dce3ef;
      box-shadow: 2px 2px 0px 0px rgba(236, 238, 252, 0.32);
      border-radius: 6px;
      margin-bottom: 8px;

      :deep .el-table th.el-table__cell {
        background-color: #ecedff;
      }
    }

    .deviceMaintain {
      position: relative;
      width: 100%;
      height: 303px;
      border: 1px solid #dce3ef;
      box-shadow: 2px 2px 0px 0px rgba(236, 238, 252, 0.32);
      border-radius: 6px;

      :deep .el-table th.el-table__cell {
        background-color: #ecedff;
      }
    }
  }

  .d-r {
    width: calc(100% - 560px);
    margin-left: 16px;

    .deviceImg {
      width: 100%;
      height: 600px;
      border: 1px solid #dce3ef;
      box-shadow: 2px 2px 0px 0px rgba(236, 238, 252, 0.32);
      border-radius: 6px;
      margin-bottom: 8px;

      .imgContainer {
        position: relative;
        width: 100%;
        height: 580px;
        margin: 0 auto;
        margin-top: 5px;
        background-repeat: no-repeat;
        background-size: 100% 100%;
        background-image: url("@/assets/images/ibe/gd.png");
        cursor: pointer;

        .tagImage {
          display: block;
          position: absolute;
          width: 52px;
          cursor: pointer;
        }
      }
    }

    .deviceTable {
      position: relative;
      width: 100%;
      height: 383px;
      border: 1px solid #dce3ef;
      box-shadow: 2px 2px 0px 0px rgba(236, 238, 252, 0.32);
      border-radius: 6px;

      :deep .el-table th.el-table__cell {
        background-color: #ecedff;
      }
    }
  }

  .modalDevice {
    width: 1400px;
    height: 570px;
    position: absolute;
    top: calc(50% - 285px);
    left: calc(50% - 700px);
    background-color: white;
    z-index: 9;
    box-shadow: 1px 2px 10px 0px rgba(225, 232, 250, 0.97);
    border: 1px #bfbfbf solid;
    border-radius: 6px;
  }
}

.title {
  position: absolute;
  width: 100px;
  height: 20px;
  border-left: 3px #8f93f7 solid;
  font-weight: bold;
  padding-left: 10px;
  margin: 15px;
}

.count {
  position: absolute;
  top: 46px;
  text-align: end;
  left: 20px;

  img {
    width: 26px;
    height: 16px;
    vertical-align: middle;
    margin-right: 15px;
  }

  .countSpan {
    color: #a495f9;
    font-size: 20px;
  }
}

.progress {
  position: absolute;
  width: 95%;
  bottom: 35px;
  padding-left: 20px;
}

.count {
  position: absolute;
  top: 46px;
  text-align: end;
  left: 20px;

  img {
    width: 26px;
    height: 16px;
    vertical-align: middle;
    margin-right: 15px;
  }

  .countSpan {
    color: #a495f9;
    font-size: 20px;
  }
}

.progress {
  position: absolute;
  width: 95%;
  bottom: 35px;
  padding-left: 20px;
}

#deviceChart {
  width: 100%;
  max-width: 441px;
  height: 335px;
}

#maintainChart {
  width: 100%;
  max-width: 441px;
  height: 335px;
}
</style>
